package io.github.gszj2018.jp_analysis;

import soot.*;
import soot.options.Options;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        if (args.length < 2) {
            System.err.println("Bad usage.");
            System.exit(1);
        }

        if ("1".equals(System.getProperty("jp_analysis_debug", "0"))) {
            Logger.v().setLogging(true);
        }

        Options.v().set_whole_program(true);
        Scene.v().setSootClassPath(args[0]);
        Scene.v().extendSootClassPath(Paths.get(args[0], "rt.jar").toString());
        Scene.v().extendSootClassPath(Paths.get(args[0], "jce.jar").toString());
        Logger.v().log("Class path: " + Scene.v().getSootClassPath());

        SootClass c = Scene.v().loadClassAndSupport(args[1]);
        Scene.v().loadNecessaryClasses();
        Scene.v().setMainClass(c);
        Logger.v().log("Main class: " + c.getName());
        Logger.v().log("Entry points:");
        for (SootMethod ep : Scene.v().getEntryPoints()) {
            Logger.v().log("    " + ep.getSignature());
        }

        AndersonSolver andersonSolver = new AndersonSolver();

        Logger.v().log("Start transform...");
        PackManager.v().getPack("wjtp").add(
                new Transform("wjtp.myjpa",
                        new ProgramTransformer(andersonSolver)));
        PackManager.v().runPacks();

        Logger.v().log("Transform done. Start solve...");
        andersonSolver.solve();

        Logger.v().log("Solve done.");
        List<String> result = andersonSolver.getPrintableResult();
        try (PrintWriter writer = new PrintWriter(new FileOutputStream("result.txt"))) {
            result.forEach(writer::println);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}
